import dotenv from 'dotenv';
import { cardSellService } from '../src/services/cardSellService';
import { telegramService } from '../src/services/telegramService';

// 加载环境变量
dotenv.config();

/**
 * 测试售卡API和Telegram通知功能（不依赖数据库）
 */
async function testCardSellApiOnly() {
  console.log('🧪 开始测试售卡API和Telegram通知功能...\n');

  try {
    // 1. 检查服务配置
    console.log('1. 检查服务配置:');
    const isCardSellConfigured = cardSellService.isConfigured();
    const isTelegramConfigured = telegramService.isConfigured();

    console.log(`   - 售卡服务配置: ${isCardSellConfigured ? '✅ 已配置' : '❌ 未配置'}`);
    console.log(`   - Telegram服务配置: ${isTelegramConfigured ? '✅ 已配置' : '❌ 未配置'}`);

    if (!isCardSellConfigured) {
      console.log('   ⚠️  请配置售卡服务后重试');
      console.log('   📝 需要在.env中配置TELEGRAM_MERCHANT_ID和TELEGRAM_SECRET_KEY');
      return;
    }

    // 2. 测试金额与产品ID映射
    console.log('\n2. 测试金额与产品ID映射:');
    const testAmounts = [275, 550, 1100, 2750, 5500, 302.5, 1925]; // 对应不同金币数量

    for (const amount of testAmounts) {
      const { coins, productId } = cardSellService.calculateCoinsAndProductId(amount);
      const status = productId ? '✅ 匹配' : '❌ 无匹配';
      console.log(`   - ${amount} THB → ${coins}M金币 → product_id=${productId || '无匹配'} ${status}`);
    }

    // 3. 测试查询用户功能
    console.log('\n3. 测试查询用户API:');
    const testUserId = 26814066;

    try {
      console.log(`   - 查询用户ID: ${testUserId}`);
      const queryResult = await cardSellService.queryUser(testUserId);

      console.log(`   - API响应码: ${queryResult.code}`);
      console.log(`   - 响应消息: ${queryResult.message}`);

      if (queryResult.code === 0) {
        console.log(`   - ✅ 查询成功`);
        console.log(`   - 玩家昵称: ${queryResult.data?.nickname || '未获取'}`);
      } else {
        console.log(`   - ❌ 查询失败: ${queryResult.message}`);
      }
    } catch (error) {
      console.log(`   - ❌ 查询用户异常: ${error instanceof Error ? error.message : '未知错误'}`);
    }

    // 4. 测试售卡功能
    console.log('\n4. 测试售卡API:');
    const testAmount = 275; // 50M金币
    const { coins, productId } = cardSellService.calculateCoinsAndProductId(testAmount);

    if (productId) {
      try {
        console.log(`   - 执行售卡: 用户${testUserId}, ${coins}M金币, product_id=${productId}`);
        const sellResult = await cardSellService.sellCard(testUserId, productId);

        console.log(`   - API响应码: ${sellResult.code}`);
        console.log(`   - 响应消息: ${sellResult.message}`);

        if (sellResult.code === 0) {
          console.log(`   - ✅ 售卡成功`);
        } else {
          console.log(`   - ❌ 售卡失败: ${sellResult.message}`);
        }
      } catch (error) {
        console.log(`   - ❌ 售卡异常: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    } else {
      console.log(`   - ⚠️ 跳过售卡测试，金额${testAmount} THB无匹配的product_id`);
    }

    // 5. 测试完整售卡流程
    console.log('\n5. 测试完整售卡流程:');
    try {
      console.log(`   - 执行完整流程: 用户${testUserId}, 金额${testAmount} THB`);
      const executeResult = await cardSellService.executeCardSell(testUserId, testAmount);

      console.log(`   - 流程结果: ${executeResult.success ? '✅ 成功' : '❌ 失败'}`);
      console.log(`   - 金币数量: ${executeResult.coins}M`);
      console.log(`   - 产品ID: ${executeResult.productId || '无匹配'}`);
      console.log(`   - 玩家昵称: ${executeResult.nickname || '未获取'}`);

      if (!executeResult.success) {
        console.log(`   - 错误信息: ${executeResult.errorMessage}`);
      }
    } catch (error) {
      console.log(`   - ❌ 完整流程异常: ${error instanceof Error ? error.message : '未知错误'}`);
    }

    // 6. 测试Telegram通知功能
    if (isTelegramConfigured) {
      console.log('\n6. 测试Telegram通知:');

      // 模拟售卡成功通知
      console.log('   6.1 测试售卡成功通知:');
      try {
        const successNotificationData = {
          orderId: 'TEST_SUCCESS_' + Date.now(),
          amount: testAmount,
          userId: testUserId,
          playerUid: testUserId.toString(),
          coins: coins,
          productId: productId,
          sellCardSuccess: true,
          playerNickname: '测试玩家',
          timestamp: new Date(),
          merchantId: process.env.TELEGRAM_MERCHANT_ID || 'DL79175852939219'
        };

        const successSent = await telegramService.sendCardSellNotification(successNotificationData);
        console.log(`      - 成功通知发送: ${successSent ? '✅ 成功' : '❌ 失败'}`);
      } catch (error) {
        console.log(`      - ❌ 成功通知异常: ${error instanceof Error ? error.message : '未知错误'}`);
      }

      // 模拟售卡失败通知
      console.log('   6.2 测试售卡失败通知:');
      try {
        const failureNotificationData = {
          orderId: 'TEST_FAILURE_' + Date.now(),
          amount: testAmount,
          userId: testUserId,
          playerUid: testUserId.toString(),
          coins: coins,
          productId: productId,
          sellCardSuccess: false,
          playerNickname: '测试玩家',
          errorMessage: '测试失败：用于演示手动充值流程',
          timestamp: new Date(),
          merchantId: process.env.TELEGRAM_MERCHANT_ID || 'DL79175852939219'
        };

        const failureSent = await telegramService.sendCardSellNotification(failureNotificationData);
        console.log(`      - 失败通知发送: ${failureSent ? '✅ 成功' : '❌ 失败'}`);
      } catch (error) {
        console.log(`      - ❌ 失败通知异常: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    } else {
      console.log('\n6. ⚠️ Telegram服务未配置，跳过通知测试');
    }

    console.log('\n🎉 售卡API和通知功能测试完成!');

    // 7. 测试结果总结
    console.log('\n📊 测试结果总结:');
    console.log(`   - 服务配置: ${isCardSellConfigured && isTelegramConfigured ? '✅ 完整' : '⚠️ 部分配置'}`);
    console.log(`   - 金额映射: ✅ 正常工作`);
    console.log(`   - 售卡API: 可用（具体结果见上方测试）`);
    console.log(`   - Telegram通知: ${isTelegramConfigured ? '可用（具体结果见上方测试）' : '❌ 未配置'}`);

  } catch (error) {
    console.error('\n❌ 测试过程中发生错误:', error);
  }
}

// 运行测试
testCardSellApiOnly().catch(console.error);